package indzcraft.ui;

import indzcraft.loader.Enchant;
import indzcraft.loader.Gem;
import indzcraft.loader.ItemEquiped;

import java.awt.Color;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;

import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingWorker;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;

public class ItemSlot extends JPanel implements ActionListener,ItemListener,MouseListener {
	
	private static final long serialVersionUID = 1L;
	private IndzCraftUI icui = null;
	private int slot;
	private ItemEquiped item = null;
	//private JButton name;
	private JButton enchant;
	private JButton[] gem = new JButton[3];
	private JLabel icon;
	private JButton reforge;
	
	
	public ItemSlot(IndzCraftUI ui,int slot,ItemEquiped item){
		//super();
		this.icui = ui;
		this.slot = slot;
		
		Border b, b1, b2;
		b1 = BorderFactory.createEmptyBorder(1, 1, 1, 1);
		b2 = BorderFactory.createLineBorder(Color.GRAY, 2);
		b = BorderFactory.createCompoundBorder(b1, b2);
		setBorder(b);
		
		// layout
		setLayout(new GridBagLayout());
		GridBagConstraints c = new GridBagConstraints();

		icon = new JLabel();
		icon.setBounds(0,0, 54, 54);
		icon.addMouseListener(this);

		c.insets = new Insets(1,1,1,1);
		c.anchor = c.anchor = GridBagConstraints.NORTHWEST; // oben links verankern
		c.fill = GridBagConstraints.BOTH;

		c.gridx = 1;
		c.gridy = 1;
		c.gridheight = 5;
		add(icon, c);
		
		enchant = new JButton();
		enchant.addActionListener(this);
		enchant.setVisible(false);
		c.gridx = 2;
		c.gridy = 1;
		c.gridheight = 1;
		add( enchant ,c );
		
		gem[0] = new JButton();
		gem[0].addActionListener(this);
		gem[0].setVisible(false);
		c.gridx = 3;
		c.gridy = 1;
		c.gridheight = 1;
		add( gem[0] ,c );
		
		gem[1] = new JButton();
		gem[1].addActionListener(this);
		gem[1].setVisible(false);
		c.gridx = 4;
		c.gridy = 1;
		add (gem[1], c);
		
		gem[2] = new JButton();
		gem[2].addActionListener(this);
		gem[2].setVisible(false);
		c.gridx = 5;
		c.gridy = 1;
		add (gem[2], c);
		

		c.gridx = 2;
		c.gridy = 2;
		c.gridwidth = 4;
		reforge = new JButton();
		//reforge.setPreferredSize(new Dimension(50, 20));
		Font f = new Font("Dialog", Font.BOLD, 9);
		reforge.setFont(f);
		reforge.setBorder(new EmptyBorder(new Insets(1,0,1,0)));
		reforge.setVisible(false);
		reforge.addActionListener(this);
		add (reforge, c);
		
		setItem(item);
	}

	public void actionPerformed(ActionEvent e) {
		if(e.getSource() == enchant)
			icui.showEnchantPanel(slot);
		else if(e.getSource() == reforge)
			icui.showReforgePanel(slot);
		else if(e.getSource() == gem[0]){
			icui.showGemPanel(slot,0);
		}
		else if(e.getSource() == gem[1]){
			icui.showGemPanel(slot,1);
		}
		else if(e.getSource() == gem[2]){
			icui.showGemPanel(slot,2);
		}
	}
	
	public void itemStateChanged(ItemEvent e) {
		if(e.getStateChange() == ItemEvent.SELECTED){
			//
		}
	}

	public void setItem(ItemEquiped item) {
		this.item = item;
		if(this.item != null){
			icon.setToolTipText(getTip());
			
			setEnchantBorder(enchant);
			changeEnchantIcon(enchant);
			if(Slot.possibleSlots[slot].isEnchantable())
				enchant.setVisible(true);
			
			for(int i = 0; i < gem.length;i++){
				setGemBorder(gem[i],i);
				changeGemIcon(gem[i],i);
			}
			
			reforge.setText(item.getReforge().getFrom().substring(0,3) + " -> " + item.getReforgeValue() + " " + item.getReforge().getTo().substring(0,3));
			reforge.setVisible(true);
			// ICON
			//System.out.println(item.getIcon());
			changeIcon(item.getIcon());
		}
		else {
			changeIcon("inv_misc_questionmark");
		}
	}
	
	public void setGemSlot(int gemSlot,Gem gem){
		item.setGem(gemSlot,gem);
		setGemBorder(this.gem[gemSlot],gemSlot);
		changeGemIcon(this.gem[gemSlot],gemSlot);
		//this.gem[gemSlot].setText(item.getGem(gemSlot).toString());
	}
	
	private void setGemBorder(JButton gem,int gemNumber) {
		Border b = null;
		gem.setVisible(true);
		if(item.gemSlot[gemNumber].equals("RED")){
			b = getGemBorder(Color.RED);
		}
		else if(item.gemSlot[gemNumber].equals("YELLOW")){
			b = getGemBorder(Color.YELLOW);
		}
		else if(item.gemSlot[gemNumber].equals("BLUE")){
			b = getGemBorder(Color.BLUE);
		}
		else if(item.gemSlot[gemNumber].equals("META")){
			b = getGemBorder(Color.LIGHT_GRAY);
		}
		else if(item.gemSlot[gemNumber].equals("PRISMATIC")){
			b = getGemBorder(Color.GRAY);
		}
		else
			gem.setVisible(false);
		gem.setBorder(b);
	}
	
	private void setEnchantBorder(JButton enchant) {
		Border b = null;
		//enchant.setVisible(true);
		if(item.getEnchant() != null){
			b = getGemBorder(Color.YELLOW);
		}
		enchant.setBorder(b);
	}

	public String getTip(){
		String text = "<html>";
		text += "<b>"+item.getName()+"</b>";
		if(item.getAgi() > 0)
		text += "<br/> + "+item.getAgi()+" Agility";
		if(item.getSta() > 0)
		text += "<br/> + "+item.getSta()+" Stamina";
		if(item.getHit() > 0)
			text += "<br/> + "+item.getHit()+" Hit Rating";
		if(item.getCrit() > 0)
			text += "<br/> + "+item.getCrit()+" Crit Rating";
		if(item.getHaste() > 0)
			text += "<br/> + "+item.getHaste()+" Haste Rating";
		if(item.getMastery() > 0)
			text += "<br/> + "+item.getMastery()+" Mastery Rating";
		if(item.getExp() > 0)
			text += "<br/> + "+item.getExp()+" Expertise Rating";
		if(item.getEnchant() != null)
			text += "<br/> Enchant: " + item.getEnchant().getName();
		if(item.getReforge() != null)
			text += "<br/> Reforge: (" + item.getReforgeValue() + ") "+item.getReforge().getFrom()+" -> "+item.getReforge().getTo();
		if(item.socketBonus != null)
			text += "<br/> " + item.socketBonus.toString();
		if(!item.getSet().equals(""))
			text += "<br/> " + item.getSet();
		text += "</html>";
		return text;
		
		/*String text = "<html>";
		text += "<head>";
		text += "<script type=text/javascript src=http://static.wowhead.com/widgets/power.js></script>";
		text += "</head><body>";
		text += icui.getLoader().getWoWHeadTooltip(item.getId());
		text += "</body></html>";*/
		//return text;
	}
	
	public ItemEquiped getItem() {
		return this.item;
	}
	
	public Border getGemBorder(Color c){
		Border b, b1, b2;
		b1 = BorderFactory.createEmptyBorder(1, 1, 1, 1);
		b2 = BorderFactory.createLineBorder(c, 1);
		b = BorderFactory.createCompoundBorder(b1, b2);
		return b;
	}
	
	public Border getEnchantBorder(Color c){
		Border b, b1, b2;
		b1 = BorderFactory.createEmptyBorder(1, 1, 1, 1);
		b2 = BorderFactory.createLineBorder(c, 1);
		b = BorderFactory.createCompoundBorder(b1, b2);
		return b;
	}

	@Override
	public void mouseClicked(MouseEvent e) {
		if(e.getSource() == icon && e.getButton() == MouseEvent.BUTTON1)
			icui.showItemPanel(slot);
		else if(e.getSource() == icon && e.getButton() == MouseEvent.BUTTON3)
			icui.showEnchantPanel(slot);
	}

	@Override
	public void mouseEntered(MouseEvent e) {
		// 
		
	}

	@Override
	public void mouseExited(MouseEvent e) {
		// 
		
	}

	@Override
	public void mousePressed(MouseEvent e) {
		// 
		
	}

	@Override
	public void mouseReleased(MouseEvent e) {
		// 
		
	}
	
	private void changeIcon(String name) {
		ChangeIconTask task = new ChangeIconTask(name);
		task.execute();
	}
	
	private class ChangeIconTask extends SwingWorker<Void,Void> {

		private String name;

		public ChangeIconTask(String name) {
			this.name = name;
		}
		
		@Override
		protected Void doInBackground() throws Exception {
			URL url = null, url2 = null;
			File file = new File("./icons/"+name+".png");
			
			if (!file.exists()) {
				//System.out.println("load from mmo-champ");
				try {
					url2 = new URL("http://db.mmo-champion.com/static/img/icons/"+name+".png");
					url = url2;
					Image image = ImageIO.read(url);
					image = createImage(new FilteredImageSource(image.getSource(),
			        new CropImageFilter(5, 5, 54, 54)));
					icon.setIcon(new ImageIcon(image));
					ReadableByteChannel rbc = Channels.newChannel(url2.openStream());
					FileOutputStream fos = new FileOutputStream(new File("./icons/"+name+".png"));
					fos.getChannel().transferFrom(rbc, 0, 1 << 24);
				}
				catch (MalformedURLException e) {}
				catch (IOException e) {}
			} else {
				//System.out.println("load from icon folder");
				try {
					Image image = ImageIO.read(file);
					image = createImage(new FilteredImageSource(image.getSource(),
			        new CropImageFilter(5, 5, 54, 54)));
					icon.setIcon(new ImageIcon(image));
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
			return null;
		}
	}
	
	public void changeGemIcon(JButton gem, int gemNumber){
		try {
			File file = null;
			if(item.gemSlot[gemNumber].equals("RED")){
				file = new File("./icons/Socket_Red.png");
			}
			else if(item.gemSlot[gemNumber].equals("YELLOW")){
				file = new File("./icons/Socket_Yellow.png");
			}
			else if(item.gemSlot[gemNumber].equals("BLUE")){
				file = new File("./icons/Socket_Blue.png");
			}
			else if(item.gemSlot[gemNumber].equals("META")){
				file = new File("./icons/Socket_Meta.png");
			}
			else if(item.gemSlot[gemNumber].equals("PRISMATIC")){
				file = new File("./icons/Socket_Meta.png");
			}
			if(file != null){
				Image image = ImageIO.read(file);
				gem.setIcon(new ImageIcon(image));
			}
			file = null;
			Gem g = item.getGem(gemNumber);
			if(g != null){
				file = new File("./icons/"+g.getIcon()+".png");
				if (file == null || !file.exists()) {
					//System.out.println("load from mmo-champ");
					try {
						URL url2 = new URL("http://db.mmo-champion.com/static/img/icons/"+g.getIcon()+".png");
						URL url = url2;
						Image image = ImageIO.read(url);
						image = createImage(new FilteredImageSource(image.getSource(),
				        new CropImageFilter(5, 5, 54, 54)));
						image = image.getScaledInstance(14, 14, Image.SCALE_DEFAULT);
						gem.setIcon(new ImageIcon(image));
						ReadableByteChannel rbc = Channels.newChannel(url2.openStream());
						FileOutputStream fos = new FileOutputStream(new File("./icons/"+g.getIcon()+".png"));
						fos.getChannel().transferFrom(rbc, 0, 1 << 24);
					}
					catch (MalformedURLException e) {}
					catch (IOException e) {}
				} else {
					//System.out.println("load from icon folder");
					try {
						Image image = ImageIO.read(file);
						image = createImage(new FilteredImageSource(image.getSource(),
				        new CropImageFilter(5, 5, 54, 54)));
						image = image.getScaledInstance(14, 14, Image.SCALE_DEFAULT);
						gem.setIcon(new ImageIcon(image));
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void changeEnchantIcon(JButton enchant){
		try {
			File file = null;
			file = new File("./icons/No_Enchant.png");

			if(file != null){
				Image image = ImageIO.read(file);
				image = createImage(new FilteredImageSource(image.getSource(),
				        new CropImageFilter(5, 5, 54, 54)));
						image = image.getScaledInstance(14, 14, Image.SCALE_DEFAULT);
				enchant.setIcon(new ImageIcon(image));
			}
			file = null;
			Enchant e = item.getEnchant();
			if(e != null){
				file = new File("./icons/inv_misc_enchantedscroll.png");
				if (file == null || !file.exists()) {
					//System.out.println("load from mmo-champ");
					try {
						URL url2 = new URL("http://db.mmo-champion.com/static/img/icons/inv_misc_enchantedscroll.png");
						URL url = url2;
						Image image = ImageIO.read(url);
						image = createImage(new FilteredImageSource(image.getSource(),
				        new CropImageFilter(5, 5, 54, 54)));
						image = image.getScaledInstance(14, 14, Image.SCALE_DEFAULT);
						enchant.setIcon(new ImageIcon(image));
						ReadableByteChannel rbc = Channels.newChannel(url2.openStream());
						FileOutputStream fos = new FileOutputStream(new File("./icons/inv_misc_enchantedscroll.png"));
						fos.getChannel().transferFrom(rbc, 0, 1 << 24);
					}
					catch (MalformedURLException oe) {}
					catch (IOException oe) {}
				} else {
					//System.out.println("load from icon folder");
					try {
						Image image = ImageIO.read(file);
						image = createImage(new FilteredImageSource(image.getSource(),
				        new CropImageFilter(5, 5, 54, 54)));
						image = image.getScaledInstance(14, 14, Image.SCALE_DEFAULT);
						enchant.setIcon(new ImageIcon(image));
					} catch (IOException oe) {
						oe.printStackTrace();
					}
				}
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
